package cc.ufinity.networkdiagnose.manager;

import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import cc.ufinity.networkdiagnose.widget.MyMobileCfgWidget;

/**
 * 获取手机信号及网络类型
 * 
 * @author ZR
 * 
 */
public final class TelManager extends AbstractManager {
    private TelephonyManager tm;
    private Context ctx;
    private MyPhoneStateListener phoneStateListener = null;
    private String strSignalStrength;
    private int cdmaDbM;
    private GsmCellLocation gsm = null;
    public static String testPhone;
    private int ber;
    private List<NeighboringCellInfo> neighborInfos;
    private int signalStrength;

    public int getSignalStrength() {
        return signalStrength;
    }

    public void setCdmaDbM(int cdmaDbM) {
        this.cdmaDbM = cdmaDbM;
    }

    public int getCdmaDbM() {
        return cdmaDbM;
    }

    private int evdoDbm;

    public void setEvdoDbm(int evdoDbm) {
        this.evdoDbm = evdoDbm;
    }

    public int getEvdoDbm() {
        return evdoDbm;
    }
    
    private int evdoSnr;    //手机信噪比
    public void setEvdoSnr(int evdoSnr) {
        this.evdoSnr = evdoSnr;
    }

    public int getEvdoSnr() {
        return evdoSnr;
    }

    public TelManager(Context context) {
        this.ctx = context;
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        phoneStateListener = new MyPhoneStateListener();
        tm.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        String networkType = getNetworkType();
        if ("EDGE".equals(networkType) || "HSDPA".equals(networkType)) {
            gsm = (GsmCellLocation) tm.getCellLocation();
        }
        //neighborInfos = new ArrayList<NeighboringCellInfo>();
        neighborInfos = tm.getNeighboringCellInfo();
        if (neighborInfos != null) {
			System.out.println(">>>>>>>>>>>>>>>>>>"+neighborInfos.size());
			for (NeighboringCellInfo neighboringCellInfo : neighborInfos) {
				 System.out.println("-相邻小区号的CID---------------->"
						+ neighboringCellInfo.getCid());
				System.out.println("-相邻小区号的LAC---------------->"
						+ neighboringCellInfo.getLac());
			}
		} else {
			System.out.println("++++++++++++++++++++++++===没有相邻小区号");
		}
        tm.listen(new PhoneStateListener() {
            @Override
            public void onDataConnectionStateChanged(int state) {
                switch (state) {
                case TelephonyManager.DATA_DISCONNECTED:// 网络断开
                	Log.d("TelephonyManager", "网络已断开");
                	System.out.println("-----AAA-----------> 网络已断开");
                    break;
                case TelephonyManager.DATA_CONNECTING:// 网络正在连接
                	Log.d("TelephonyManager", "正在连接网络");
                	System.out.println("------BBB----------> 正在连接网络");
                    break;
                case TelephonyManager.DATA_CONNECTED:// 网络连接上
                	Log.d("TelephonyManager", "网络连接成功");
                	System.out.println("------CCC----------> 网络连接成功");
                    break;
                }
            }

        }, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    }

    public int getLac() {
        return (gsm != null) ? gsm.getLac() : 0;
    }

    /**
     * 
     * 这个方法是为了解析并获取3G的CI
     * @param a
     * @return
     */
    public  int init(int a){
		String b = Integer.toBinaryString(a);// 转化成2进制
		System.out.println("" + b);
		if(b.length() <= 16) {
			System.out.println("3G 错误    CI -------->  " + b);
			return a;
		}
		String str2 = b.substring(0, b.length() - 16);// 截取去掉后面16位的剩下的部分
		String str3 = b.substring( b.length() - 16);// 截取去掉后面16位的剩下的部分
System.out.println("" + str2);
		int e = Integer.valueOf(str2, 2);// 在转化成10进制()
		int f = Integer.valueOf(str3, 2);// 在转化成10进制()
		int g=e*65536+f;
		System.out.println("干扰信号" +e+"CI"+f+"最后的结果"+g );	
		return f;
	}
    
    public int getCI() {
    	//CdmaCellLocation
    	try {
    		gsm = (GsmCellLocation) tm.getCellLocation();
    	} catch(Exception e) {
    		Log.e("TelManager", "getCI" , e);
    	}
    	
    	int ci = (gsm != null) ? gsm.getCid() : 0;
    	String b = Integer.toBinaryString(ci);// 转化成2进制
		System.out.println("" + b);
		if(b.length() > 16) {
			ci = init(ci);
		}
		
		return ci;
		
    	/*if(getNetworkType().equals("HSDPA")&&gsm!=null){
    		int a=gsm.getCid();//获取的是3G下面的CI
    		int b=init(a);
    		return b;
    	}else{
    		return (gsm != null) ? gsm.getCid() : 0;
    	}*/
    }
 
    public String getPhoneNumber() {
        //String tel = tm.getLine1Number();
        String tel = "";
        //if (StringUtils.isEmpty(tel)) {
            SharedPreferences settings = ctx.getSharedPreferences(MyMobileCfgWidget.PREFS_NAME, 0);
            tel = settings.getString(MyMobileCfgWidget.PREFS_KEY, "");
            testPhone = tel;
            Log.d("getPhoneNumber", "配置的本机号码:"+tel);
        //}
        return tel;
        //return "13966770621";
    }

    public String getNetworkType() {
        String s = null;
        int a = tm.getNetworkType();
        if (a == TelephonyManager.NETWORK_TYPE_1xRTT) {
            s = "1xRTT";
        } else if (a == TelephonyManager.NETWORK_TYPE_CDMA) {
            s = "CDMA";
        } else if (a == TelephonyManager.NETWORK_TYPE_EDGE) {  //移动GSM
            s = "EDGE";
        } else if (a == TelephonyManager.NETWORK_TYPE_EVDO_0) {
            s = "EVD0_0";
        } else if (a == TelephonyManager.NETWORK_TYPE_EVDO_A) {  //电信
            s = "EVD0_A";
        } else if (a == TelephonyManager.NETWORK_TYPE_GPRS) {
            s = "GPRS";
        } else if (a == TelephonyManager.NETWORK_TYPE_HSDPA) {  //移动TD
            s = "HSDPA";
        } else if (a == TelephonyManager.NETWORK_TYPE_HSPA) {  //联通
            s = "HSPA";
        } else if (a == TelephonyManager.NETWORK_TYPE_HSUPA) {
            s = "HSUPA";
        } else if (a == TelephonyManager.NETWORK_TYPE_UMTS) {
            s = "UMTS";
        } else {
            s = "UNKNOW";
        }
        return s;
    }
    /**
     *
	 * 当前使用的网络类型： 例如：
	 *  NETWORK_TYPE_UNKNOWN 网络类型未知 0 
	 *  NETWORK_TYPE_GPRS GPRS网络1 
	 *  NETWORK_TYPE_EDGE EDGE网络 2 
	 *  NETWORK_TYPE_UMTS UMTS网络 3
	 *  NETWORK_TYPE_CDMA CDMA网络,IS95A 或 IS95B. 4
	 *  NETWORK_TYPE_EVDO_0 EVDO网络, revision 0. 5 
	 *  NETWORK_TYPE_EVDO_A EVDO网络,revision A. 6 
	 *  NETWORK_TYPE_1xRTT 1xRTT网络 7
	 *  NETWORK_TYPE_HSDPA HSDPA网络 8 
	 *  NETWORK_TYPE_HSUPA HSUPA网络 9
	 *  NETWORK_TYPE_HSPA HSPA网络 10 
     * @return
     */
    public int getChinaMobileNetworkType() {
    	return tm.getNetworkType();
    }

    public int getBER() {
        return ber;
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        public void onSignalStrengthsChanged(SignalStrength sStrength) {
            super.onSignalStrengthsChanged(sStrength);// 调用超类的该方法，在网络信号变化时得到回答信号
            StringBuffer s = new StringBuffer();
            ber = sStrength.getGsmBitErrorRate();
            signalStrength = sStrength.getGsmSignalStrength();
 //           System.out.println(sStrength.getGsmSignalStrength()+" -------------------------------->1");
            signalStrength = sStrength.getEvdoDbm();//
//			 System.out.println(sStrength.getEvdoDbm()+" -------------------------------->2");
            if (sStrength.isGsm()) { 
                if (sStrength.getGsmSignalStrength() != 99) 
                	signalStrength = sStrength.getGsmSignalStrength() * 2 - 113; 
                else 
                	signalStrength = sStrength.getGsmSignalStrength(); 
            } else { 
            	signalStrength = sStrength.getCdmaDbm(); 
             	System.out.println(sStrength.getCdmaDbm()+" -------------------------------->3");
            } 
            if(signalStrength <0)
            	signalStrength *= -1;
            s.append("-").append(signalStrength);
            setStrSignalStrength(s.toString());
            setEvdoDbm(sStrength.getEvdoDbm());
            setCdmaDbM(sStrength.getCdmaDbm());
            setEvdoSnr(sStrength.getEvdoSnr()); //手机信噪比
            sendMsg(MessageWhat.TEL_STATE_SUCCESS);
        }
    }

    public String getStrSignalStrength() {
    	
        return strSignalStrength;
    }
    
    public void setStrSignalStrength(String strSignalStrength) {
        this.strSignalStrength = strSignalStrength;
    }

	public List<NeighboringCellInfo> getNeighborInfos() {
		return neighborInfos;
	}

	public void setNeighborInfos(List<NeighboringCellInfo> neighborInfos) {
		this.neighborInfos = neighborInfos;
	}

}
